<template>
  <el-tree-select
    v-model="value"
    :data="depts"
    :props="props"
    :multiple="multiple"
    check-strictly
    show-checkbox
    collapse-tags
    collapse-tags-tooltip
    :max-collapse-tags="5"
    value-key="id"
    filterable
    clearable
    :disabled="disabled"
    :placeholder="placeholder"
    @blur="$emit('change', value)"
    @change="
      () => {
        if (!multiple) {
          $refs.treeSelect.blur()
        }
      }
    "
  />
</template>
<script>
import { fetchDeptTree } from '@/api/loginUser/common'

export default {
  name: 'DeptTreeSelect',
  emits: ['update:modelValue', 'change'],
  props: {
    modelValue: {
      required: true,
    },
    placeholder: {
      default: () => {
        return '请选择所属部门'
      },
    },
    disabled: {
      type: Boolean,
      default: () => {
        return false
      },
    },
    multiple: {
      type: Boolean,
      default: () => {
        return false
      },
    },
    showAll: {
      type: Boolean,
      default: () => {
        return false
      },
    },
  },
  data() {
    return {
      props: {
        value: 'id',
        label: 'deptName',
      },
      allDepts: [],
    }
  },
  mounted() {
    if (this.showAll) {
      fetchDeptTree(0).then((res) => {
        this.allDepts = res.data.data
        this.allDepts.push({
          id: 0,
          deptName: '根部门',
        })
      })
    }
  },
  computed: {
    depts() {
      return this.showAll ? this.allDepts : this.$store.getters.depts
    },
    value: {
      get() {
        return this.modelValue
      },
      set(value) {
        this.$emit('update:modelValue', value)
      },
    },
  },
}
</script>
